package edu.hubu.commons.handler;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.hubu.commons.model.CommonResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Retain
 * @date 2021/2/16 10:39
 */
public class CustomUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        CommonResult result = null;
        // 被限流
        if (e instanceof FlowException){
            result=new CommonResult().setCode(429).setCurrentPage(1)
                    .setMessage("系统繁忙，请稍后再试--限流")
                    .setTotal(1);
        }
        // 降级异常
        else if (e instanceof DegradeException){
            result=new CommonResult().setCode(430).setCurrentPage(1)
                    .setMessage("系统异常，请稍后再试--降级")
                    .setTotal(1);
        }
        // 热点资源限流
        else if (e instanceof ParamFlowException){
            result=new CommonResult().setCode(431).setCurrentPage(1)
                    .setMessage("该资源访问繁忙，请稍后再试--热点")
                    .setTotal(1);
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type","application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(response.getWriter(),result);
    }
}
